﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sio.Mdm.Server;
using Sio.Mdm.Entities;
using Sio.Mdm.Types.Database;
using System.Reflection;
using Sio.Mdm.Security;
using System.Configuration;

namespace Sio.Mdm.Web.Base
{
	public class SecurityTokenWriter : IInvokeInterceptor
	{
        #region SecurityTokenWriteEnabled
        /// <summary>
        /// Get wheater writing of security tokens is enabled. This should be turned 
        /// off when running final version. It can also be turned off in web.config.
        /// Just set "SecurityTokenEnableWrite" key to false.
        /// </summary>
        protected bool SecurityTokenWriteEnabled
        {
            get
            {
                string value = ConfigurationManager.AppSettings["SecurityTokenEnableWrite"];
                bool result = false;

                if (!String.IsNullOrEmpty(value))
                {
                    result = value.ToLower() == "true";
                }

                return result;
            }
        }
        #endregion

        #region IInvokeInterceptor Members
        bool IInvokeInterceptor.BeforeInvoke(System.Reflection.MethodInfo method, object[] args, string proxyName, out object result)
        {
            if (!SecurityTokenWriteEnabled)
            {
                result = null;
                return true;
            }

            Type entityType = SecurityTokenCache.ExtractTokenType(method);

            if (entityType != typeof(VarnostniZeton))
            {
                string tokenName = String.Empty;

                if (entityType == null)
                {
                    tokenName = String.Format(
                        "{1}.{0}",
                        method.Name,
                        proxyName.Replace("Castle.Proxies.", "").Replace("Proxy", "")
                    );
                }
                else
                {
                    tokenName = String.Format(
                        "{1}.{0}",
                        entityType.Name,
                        proxyName.Replace("Castle.Proxies.", "").Replace("Proxy", "")
                    );
                }

                SecurityTokenCache.AddToken(tokenName);
            }

            result = null;
            return true;
        }

        void IInvokeInterceptor.AfterInvoke(System.Reflection.MethodInfo method, object[] args, object result, InvocationError error)
        {   
        }
        #endregion
    }

    
}
